package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dataDAOImpl.MySQLCommodityDAO;
import dataDAOImpl.MySQLRecipeCompDAO;
import dataDAOImpl.MySQLRecipeDAO;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.ICommodityDAO;
import dataDAOInterfaces.IRecipeCompDAO;
import dataDAOInterfaces.IRecipeDAO;
import dataDTO.CommodityDTO;
import dataDTO.RecipeCompDTO;
import dataDTO.RecipeDTO;
import service.DataService;
import service.ErrorService;
import service.ValidateCommodity;
import service.ValidateRecipe;
import service.ValidateRecipeKomponent;

/**
 * Servlet implementation class Farma
 */
public class Farma extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Farma() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	private ValidateCommodity validateCommodity = new ValidateCommodity();
	private ValidateRecipe validateRecipe = new ValidateRecipe();
	private ValidateRecipeKomponent validateRecipeKomponent = new ValidateRecipeKomponent();
	private DataService data = new DataService();
	private RequestDispatcher dispatcher;
	private ICommodityDAO comm;
	private CommodityDTO commObj;
	private IRecipeDAO rec;
	private IRecipeCompDAO recComp;
	private String nr;
	private String name;
	private String supplier;
	private String page;
	private String id;
	private String nomNetto;
	private String tolorance;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		page = request.getParameter("page");
		id = request.getParameter("id");
		if (isLoggedIn(request))
		{
			try
			{
				if (page.equals("1"))		// DEFAULT PAGE
				{
					this.forward(request, response, "/WEB-INF/farma/Default.jsp");
				}
				//############################################## CREATE COMMODITY PAGE ##############################################
				else if (page.equals("2"))
				{
					if (!request.getMethod().equals("POST"))
					{
						this.forward(request, response, "/WEB-INF/farma/CreateCommodity.jsp");
					}
					else
					{
						this.createCommodity(request, response);
					}
				}
				//############################################## EDIT COMMODITY PAGE ##############################################
				else if (page.equals("3"))
				{
					if (!request.getMethod().equals("POST"))
					{
						this.setBeanData(request, response);
					}
					else
					{
						this.updateCommodity(request, response);
					}
				}
				//############################################## SHOW RECIPES PAGE ##############################################
				else if (page.equals("4"))
				{
					this.forward(request, response, "/WEB-INF/farma/ShowRecipes.jsp");
				}
				//############################################## CREATE RECIPE PAGE ##############################################
				else if (page.equals("5"))
				{
					if (!request.getMethod().equals("POST"))
					{
						this.forward(request, response, "/WEB-INF/farma/CreateRecipe.jsp");
					}
					else
					{
						this.createRecipe(request, response);
					}
				}
				//############################################## SHOW RECIPE COMPONENTS ##############################################
				else if (page.equals("6"))
				{
					data.setRecipeId(id);
					request.setAttribute("DataService", data);	//Sender objektet med requestet
					this.forward(request, response, "/WEB-INF/farma/RecipeComponents.jsp");
				}

				//############################################## ADD COMMODITYCOMPONENTS ON RECIPE  ###################################

				else if (page.equals("7"))
					if (!request.getMethod().equals("POST"))
					{	
						data.setRecipeId(id);
						request.setAttribute("DataService", data);	//Sender objektet med requestet
						this.forward(request, response, "/WEB-INF/farma/AddCommodity.jsp");
					}
					else
					{
						this.createRecipeKomponent(request, response);
					}
			}
			catch (NullPointerException e)
			{
				//Der kastes NullPointerException hvis man ikke angiver page attributten i URLen
				//Derfor forwardes til default
				this.forward(request, response, "/WEB-INF/farma/Default.jsp");
				System.out.println("Fejl: "+e);
			}
		}
		else	//Hvis man ikke er logget ind
		{
			this.forward(request, response, "/Afvejningssystem");
		}
	}

	//################################################### METHODS ###################################################
	private boolean isLoggedIn(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return Integer.parseInt(session.getAttribute("user").toString()) <= 2;	//Her får både rolle 1 og 2 adgang (admin og farmaceut)
	}

	private void forward(HttpServletRequest request, HttpServletResponse response, String URL) throws ServletException, IOException
	{
		dispatcher = request.getRequestDispatcher(URL);
		dispatcher.forward(request, response);
	}

	private void createCommodityError(HttpServletRequest request)
	{
		ErrorService error = validateCommodity.createError();
		error.setError(validateCommodity.getError());
		request.setAttribute("error", error);
	}

	private void createRecipeError(HttpServletRequest request)
	{
		ErrorService error = validateRecipe.createError();
		error.setError(validateRecipe.getError());
		request.setAttribute("error", error);
	}
	
	private void createRecipeKomponentError(HttpServletRequest request)
	{
		ErrorService error = validateRecipeKomponent.createError();
		error.setError(validateRecipeKomponent.getError());
		request.setAttribute("error", error);
	}

	private void createCommodity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		nr = request.getParameter("commodityNr");
		name = request.getParameter("commodityName");
		supplier = request.getParameter("commoditySupplier");
		if (!validateCommodity.validate(nr, name, supplier)) //Hvis felterne ikke er udfyldt korrekt udskrives der fejlbesked
		{
			this.createCommodityError(request);
			this.forward(request, response, "/WEB-INF/farma/CreateCommodity.jsp");
		} 
		else
		{
			comm = new MySQLCommodityDAO();
			try
			{
				comm.createCommodity(new CommodityDTO(Integer.parseInt(nr), name, supplier));
				this.forward(request, response, "/WEB-INF/farma/Default.jsp");
			}
			catch (DALException e) 
			{
				validateCommodity.setError("<li>Råvarenummer er i brug</li>");
				this.createCommodityError(request);
				this.forward(request, response, "/WEB-INF/farma/CreateCommodity.jsp");
				System.out.println("Fejl: "+e);
			}
		}
	}

	private void setBeanData(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			comm = new MySQLCommodityDAO();
			commObj = comm.getCommodity(Integer.parseInt(id));
			data.setCommodityName(commObj.getCommodityName()); //Sætter data i bønnen så det vises når siden loades
			data.setCommodityNr(Integer.toString(commObj.getCommodityId()));
			data.setCommoditySupplier(commObj.getSupplier());
			request.setAttribute("DataService", data);	//Sender objektet med requestet
			this.forward(request, response, "/WEB-INF/farma/EditCommodity.jsp");
		}
		catch (DALException e)
		{
			System.out.println("DAL Fejl: "+e);
		}
		catch (Exception e)
		{
			System.out.println("Fejle: "+e);
		}
	}

	private void updateCommodity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		nr = request.getParameter("id");
		name = request.getParameter("commodityName");
		supplier = request.getParameter("commoditySupplier");
		if (!validateCommodity.validate(nr, name, supplier)) //Hvis felterne ikke er udfyldt korrekt udskrives der fejlbesked
		{
			this.createCommodityError(request);
			this.forward(request, response, "/WEB-INF/farma/EditCommodity.jsp");
		}
		else
		{
			try
			{
				commObj = new CommodityDTO(Integer.parseInt(nr), name, supplier);
				comm.updateCommodity(commObj);
				this.forward(request, response, "/WEB-INF/farma/Default.jsp");
			}
			catch (DALException e)
			{
				System.out.println("DAL Fejl: "+e);
			}
			catch (Exception e)
			{
				System.out.println("Fejl: "+e);
			}
		}
	}

	private void createRecipe(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		nr = request.getParameter("recipeId");
		name = request.getParameter("recipeName");
		if (!validateRecipe.validate(nr, name)) //Hvis felterne ikke er udfyldt korrekt udskrives der fejlbesked
		{
			this.createRecipeError(request);
			this.forward(request, response, "/WEB-INF/farma/CreateRecipe.jsp");
		} 
		else
		{
			rec = new MySQLRecipeDAO();
			try
			{
				rec.createRecipe(new RecipeDTO((Integer.parseInt(nr)), name));
				this.forward(request, response, "/WEB-INF/farma/ShowRecipes.jsp");
			}
			catch (DALException e) 
			{
				validateRecipe.setError("<li>Recept ID i brug</li>");
				this.createRecipeError(request);
				this.forward(request, response, "/WEB-INF/farma/CreateRecipe.jsp");
				System.out.println("DAL Fejl: "+e);
			}
			catch (Exception e) 
			{
				System.out.println("Fejl: "+e);
			}
		}
	}

	private void createRecipeKomponent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String[] nr = request.getParameter("commodityName").split(" ");
		nomNetto = request.getParameter("nonNetto");
		tolorance = request.getParameter("tolerance");
				
		if (!validateRecipeKomponent.validate(nr[0], nomNetto, tolorance)) //Hvis felterne ikke er udfyldt korrekt udskrives der fejlbesked
		{
			this.createRecipeKomponentError(request);
			this.forward(request, response, "/WEB-INF/farma/AddCommodity.jsp");
		} 
		else
		{
			recComp = new MySQLRecipeCompDAO();
			try
			{
				recComp.createRecipeComp(new RecipeCompDTO(Integer.parseInt(request.getParameter("id")), Integer.parseInt(nr[0]), Double.parseDouble(nomNetto), Double.parseDouble(tolorance)));
				this.forward(request, response, "/WEB-INF/farma/ShowRecipes.jsp");
			}
			catch (DALException e) 
			{
				validateRecipe.setError("<li>Råvare er allerede tilføjet</li>");
				this.createRecipeError(request);
				this.forward(request, response, "/WEB-INF/farma/AddCommodity.jsp");
				System.out.println("DAL Fejl: "+e);
			}
			catch (Exception e) 
			{
				System.out.println("Fejl: "+e);
			}
		}
	}
}
